<template>
  <n-space class="essay" vertical>
    <n-space justify="space-between">
      <n-button @click="createArticle"> 新建文章 </n-button>
      <n-form
        ref="formRef"
        inline
        :label-width="80"
        :model="formValue"
        label-placement="left"
        :rules="rules"
      >
        <n-form-item label="标题" path="title">
          <n-input v-model:value="formValue.title" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-select
            v-model:value="formValue.status"
            clearable
            :options="options"
          />
        </n-form-item>
        <n-form-item>
          <n-button @click="findClick"> 查询 </n-button>
        </n-form-item>
      </n-form>
    </n-space>
    <n-data-table
      remote
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      :row-key="rowKey"
      @update:page-size="handlePageSizeChange"
      @update:page="handlePageChange"
    />
  </n-space>
</template>

<script setup lang="ts">
import {
  type FormInst,
  type FormItemRule,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSelect,
  NSpace,
  NDataTable,
  NTag,
  NImage,
  type SelectOption,
  type SelectGroupOption,
  type DataTableColumns,
} from "naive-ui";
import {
  findAll as apiPostFindAll,
  removeOne,
  type PostListShow,
  type PostQueryFind,
} from "../../api/post";
import PostEdit from "@/components/Post/Edit.vue";
useHead({
  title: "文章列表", //网站标题
});

definePageMeta({
  title: "文章管理-文章列表",
});
const createArticle = async () => {
  await navigateTo({
    path: "/post/writeContent",
  });
};
const formRef = ref<FormInst | null>();
const formValue = ref<PostQueryFind>({
  title: "",
  status: undefined,
});
const rules = {
  title: {
    pattern: /^.{0,10}$/,
    message: "查询长度小于10",
    trigger: "input",
  },
};
const options: Array<SelectOption | SelectGroupOption> = [
  {
    label: "发版",
    value: "publish",
  },
  {
    label: "草稿",
    value: "draft",
  },
];

const findClick = (e: MouseEvent) => {
  e.preventDefault();
  const messageReactive = naiveui.message.loading("查询中", {
    duration: 0,
  });
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      listFind();
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
    messageReactive.destroy();
  });
};

const createColumns = ({
  play,
  edit,
  del,
}: {
  play: (row: PostListShow) => void;
  edit: (row: PostListShow) => void;
  del: (row: PostListShow) => void;
}): DataTableColumns<PostListShow> => {
  return [
    {
      title: "文章名",
      key: "title",
    },
    {
      title: "封面地址",
      key: "coverUrl",
      render(row) {
        return h(NImage, {
          width: "50",
          src:
            row.coverUrl ??
            "https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg",
        });
      },
    },
    {
      title: "状态",
      key: "status",
      render(row) {
        return row.status === "publish" ? "已发布" : "草稿";
      },
    },
    {
      title: "作者",
      key: "author",
      render(row) {
        return row.author?.nickname ?? "未知";
      },
    },
    {
      title: "分类",
      key: "category",
      render(row) {
        return row.category?.name ?? "未分类";
      },
    },
    {
      title: "标签",
      key: "tags",
      render(row) {
        const tags = row.tags.map((tagKey) => {
          return h(
            NTag,
            {
              style: {
                marginRight: "6px",
              },
              type: "info",
              bordered: false,
            },
            {
              default: () => tagKey.name,
            }
          );
        });
        return tags;
      },
    },
    {
      title: "浏览数",
      key: "count",
    },
    {
      title: "点赞数",
      key: "likeCount",
    },
    {
      title: "",
      key: "actions",
      render(row: PostListShow) {
        return [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              style: {
                "margin-right": "10px",
              },
              onClick: () => play(row),
            },
            { default: () => "内容修改" }
          ),
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              style: {
                "margin-right": "10px",
              },
              onClick: () => edit(row),
            },
            { default: () => "编辑" }
          ),
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              onClick: () => del(row),
            },
            { default: () => "删除" }
          ),
        ];
      },
    },
  ];
};

const data = ref<PostListShow[]>([]);

const columns = createColumns({
  async play(row: PostListShow) {
    await navigateTo({
      path: "/post/writeContent",
      query: { id: row.id },
    });
  },
  edit(row: PostListShow) {
    naiveui.dialog.create({
      title: "文章管理",
      content: () =>
        h(PostEdit, {
          id: row.id,
          onAfterUpdate: () => {
            listFind();
          },
        }),
    });
  },
  del(row: PostListShow) {
    removeOne(row.id).then(() => {
      listFind();
    });
  },
});
const rowKey = (rowData: { id: any }) => {
  return rowData.id;
};
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  listFind();
};
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  listFind();
};
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageSizes: [3, 5, 7],
});
const listFind = async () => {
  const res = await apiPostFindAll({
    ...formValue.value,
    pageNum: pagination.value.page,
    pageSize: pagination.value.pageSize,
  });
  data.value = res.data.list;
  pagination.value.itemCount = res.data.count;
};
onMounted(() => {
  listFind();
});
</script>
<style lang="scss" scoped>
.essay {
  padding: 20px 15px;
  .n-input,
  .n-select {
    width: 200px;
  }
  .n-pagination {
    justify-content: center;
  }
}
</style>
